package com.example.mychat.Service;

import com.example.mychat.Dao.userDao;
import com.example.mychat.Pojo.Result;
import com.example.mychat.Pojo.UserInfo;
import com.example.mychat.Utils.JWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@Slf4j
public class UserService {

    ArrayList<String> CaptchaList = new ArrayList<>();

    @Autowired
    private userDao userdao;

    @Autowired
    private MailService mailService;

    /**
     * 用户登录验证
     *
     * @param userInfo 实体类
     * @return
     */
    public Result login(UserInfo userInfo) {
        log.info("" + userInfo);
        Result result = null;
        UserInfo login1 =null;
        if(userInfo.getPhone()!=null){
            login1 = userdao.Login_selectPhone(userInfo);
        }else if(userInfo.getAddress()!=null){
            login1 = userdao.Login_selectEmail(userInfo);
        }else{
            login1 = userdao.Login_select(userInfo);
        }

        if (login1 != null) {
            if (login1.getId() != null) {
                log.info(login1.getId());
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", login1.getId());
                claims.put("name", login1.getName());
                String jwt = JWT.generateJWT(claims);
                login1.setJwt(jwt);
                result = Result.success(login1);
            } else {
                log.info("账号或密码错误");
                result = Result.error("账号或密码错误");
            }
        }
        return result;
    }

    /**
     * 发送邮件验证
     *
     * @param addressee 用户电子邮件地址
     * @return 发送成功或失败
     */
    public Result sendEmail(String addressee) {
        Result result = null;
        try {
            String Captcha = createCaptcha();
            log.info(Captcha);
            String subject = "MyChat新用户注册";
            String text = "你好亲爱的用户:\n欢迎注册本网站,您的验证码为:" + Captcha + "\t,验证码有效时间为2分钟,请尽快填写!";
            mailService.sendTextMailMessage(addressee, subject, text);
            removeCaptcha(Captcha);
            result = Result.success();
        } catch (Exception e) {
            log.info("邮件发送失败" + e);
            result = Result.error("邮件发送失败");
        }
        return result;
    }

    /**
     * 注册操作
     *
     * @param userInfo 用户传递进来的信息
     * @return 注册结果-成功/失败
     */
    public Result signUp(UserInfo userInfo) {
        Result result = null;
        String captcha = userInfo.getCaptcha();
        log.info(captcha);
        int index = CaptchaList.indexOf(captcha);
        if (index != -1) {
            CaptchaList.remove(index);
            log.info("验证成功");
            String count = userdao.SelectUsernum(userInfo.getPhone(),userInfo.getAddress());
            if (count == null || count == "") {
                userdao.userInsert(userInfo);
                result = Result.success();
            } else {
                result = Result.error("该用户已被注册!");
            }
        }else{
            result = Result.error("验证码错误!");
        }
        return result;
    }


    public Result resetUserPasswd(UserInfo userInfo) {
        Result result = null;
        String id = userInfo.getId();
        String oldpasswd = userInfo.getPassword();

        if (id != null && oldpasswd != null && id != "" && oldpasswd != "") {
            UserInfo res = userdao.Login_select(userInfo);
            if (res != null) {
                if (res.getId() != null && res.getId() != "") {
                    int num = userdao.resetPasswd(userInfo.getNewPassword(), id);
                    if (num > 0) {
                        result = Result.success();
                    }
                } else {
                    result = Result.error("未找到当前用户");
                    log.info("未找到当前用户");
                }
            } else {
                result = Result.error("原密码输入错误");
                log.info("原密码输入错误");
            }
        } else {
            result = Result.error("用户信息获取失败,请重新登录");
            log.info("用户信息获取失败,请重新登录");
        }
        return result;
    }

    /**
     * 动态生成验证码
     *
     * @return 验证码
     */
    public String createCaptcha() {
        char[] str = "abcdefghijklmnopqrstuvwxyz".toCharArray();
        String Captcha = "";
        for (int i = 0; i < 4; i++) {
            Captcha += Integer.toString((int) (Math.random() * 10));
        }
        for (int s = 0; s < 2; s++) {
            String strings = String.valueOf(str[(int) (Math.random() * str.length)]);
            Captcha += strings;
        }
        pushToC_List(Captcha);
        return Captcha;
    }

    /**
     * 存储到公共的暂存区
     *
     * @param captcha
     */
    public void pushToC_List(String captcha) {
        CaptchaList.add(captcha);
        log.info(CaptchaList.toString());
    }

    public void removeCaptcha(String captcha) {
        new Thread(() -> {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //在计时器任务中将Captcha设置为null
                    int index = CaptchaList.indexOf(captcha);
                    if (index != -1) {
                        CaptchaList.remove(index);
                    }
                    timer.cancel();
                }
            }, 2 * 60 * 1000);//2分钟
        });
    }

}
